<template>
  <view class="content">
    <view class="register-form">
      <u-form labelPosition="top" :model="form" :rules="rules" ref="uForm">
        <u-form-item label="公司图片" borderBottom>
          <u-upload :fileList="fileList1" maxCount="1" @delete="deletePic" @afterRead="afterRead" name="1" />
        </u-form-item>
        <u-form-item label="公司名称" prop="demandUnit" borderBottom>
          <u-input v-model="form.demandUnit" placeholder="请输入公司名称" border="none"></u-input>
        </u-form-item>
        <u-form-item label="岗位类型" prop="jobType" borderBottom>
          <u-input v-model="form.jobTypeName" placeholder="点击右侧按钮选择" readonly border="none">
            <template #suffix>
              <view class="right-icon" @click="jobTypePicker.show = true">
                <text>选择</text>
                <u-icon name="arrow-right"></u-icon>
              </view>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item label="联系人" prop="contactPerson" borderBottom>
          <u-input v-model="form.contactPerson" placeholder="请输入联系人" border="none"></u-input>
        </u-form-item>
        <u-form-item label="联系电话" prop="contactPhone" borderBottom>
          <u-input v-model="form.contactPhone" type="number" placeholder="请输入联系电话" border="none"></u-input>
        </u-form-item>
        <u-form-item label="年龄" prop="age" borderBottom>
          <u-input v-model="form.age" placeholder="请输入年龄" border="none"></u-input>
        </u-form-item>
        <u-form-item label="学历" prop="educational" borderBottom>
          <u-input v-model="form.educationalName" placeholder="点击右侧按钮选择" readonly border="none">
            <template #suffix>
              <view class="right-icon" @click="educationalPicker.show = true">
                <text>选择</text>
                <u-icon name="arrow-right"></u-icon>
              </view>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item label="性别" prop="gender" borderBottom>
          <u-input v-model="form.genderName" placeholder="点击右侧按钮选择" readonly border="none">
            <template #suffix>
              <view class="right-icon" @click="genderPicker.show = true">
                <text>选择</text>
                <u-icon name="arrow-right"></u-icon>
              </view>
            </template>
          </u-input>
        </u-form-item>
        <u-form-item label="薪资" prop="rent" borderBottom>
          <u-input v-model="form.rent" placeholder="请输入薪资" border="none"></u-input>
        </u-form-item>
        <u-form-item label="公司介绍" prop="content" borderBottom>
          <u-textarea v-model="form.content" placeholder="请输入公司介绍" border="none" />
        </u-form-item>
      </u-form>
    </view>
    <view class="submit">
      <u-button type="primary" text="发布" @click="submit"></u-button>
    </view>

    <u-picker
      :show="jobTypePicker.show"
      :columns="jobTypePicker.columns"
      :loading="jobTypePicker.loading"
      keyName="dictLabel"
      @confirm="jobTypeConfirm"
      @cancel="jobTypePicker.show = false"
    ></u-picker>

    <u-picker
      :show="educationalPicker.show"
      :columns="educationalPicker.columns"
      :loading="jobTypePicker.loading"
      keyName="dictLabel"
      @confirm="educationalConfirm"
      @cancel="educationalPicker.show = false"
    ></u-picker>

    <u-picker
      :show="genderPicker.show"
      :columns="genderPicker.columns"
      :loading="genderPicker.loading"
      keyName="dictLabel"
      @confirm="genderConfirm"
      @cancel="genderPicker.show = false"
    ></u-picker>
  </view>
</template>

<script>
import communityApi from '../request/api/community'
import toolApi from '../request/api/tool'
import { mapState } from 'vuex'
import config from '../request/config'
const baseForm = {
  demandUnit: '',
  jobType: '',
  contactPerson: '',
  contactPhone: '',
  age: '',
  educational: '',
  gender: '',
  rent: '',
  jobTime: '',
  content: '',
}
export default {
  data() {
    return {
      form: { ...baseForm },
      rules: {
        demandUnit: [{ required: true, message: '请填写单位名称', trigger: ['blur'] }],
        jobType: [{ required: true, message: '请选择岗位类型', trigger: ['blur'] }],
        contactPerson: [{ required: true, message: '请填写联系人', trigger: ['blur'] }],
        contactPhone: [
          { required: true, message: '请填写联系电话', trigger: ['blur'] },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请填写正确的手机号', trigger: ['blur'] },
        ],
        age: [
          { required: true, message: '请填写年龄', trigger: ['blur'] },
          { pattern: /^[1-9]\d*$/, message: '请填写正确的年龄', trigger: ['blur'] },
        ],
        educational: [{ required: true, message: '请选择学历', trigger: ['blur'] }],
        gender: [{ required: true, message: '请选择性别', trigger: ['blur'] }],
        rent: [{ required: true, message: '请填写薪资', trigger: ['blur'] }],
        content: [{ required: true, message: '请填写公司介绍', trigger: ['blur'] }],
      },
      fileList1: [],
      // 岗位类型
      jobTypePicker: {
        show: false,
        loading: false,
        columns: []
      },
      // 学历
      educationalPicker: {
        show: false,
        loading: false,
        columns: []
      },
      // 性别
      genderPicker: {
        show: false,
        loading: false,
        columns: []
      },
    }
  },
  computed: {
    ...mapState('userInfo', ['user']),
  },
  async onLoad() {
    await this.$store.dispatch('userInfo/GetInfo')
    if (!this.user.postStatus) return uni.showModal({
      title: '提示',
      content: '该账号未实名认证，请点击我的个人信息填写实名信息，等待管理员认证通过可发布信息。',
      showCancel: false,
      confirmText: '返回',
      success: () => {
        uni.navigateBack();
      }
    })
    this.$refs.uForm.setRules(this.rules)
    this.jobTypePicker.loading = true
    toolApi.getDicts('job_type').then(res => {
      this.jobTypePicker.loading = false
      this.jobTypePicker.columns = [res.data]
    })
    this.educationalPicker.loading = true
    toolApi.getDicts('educational').then(res => {
      this.educationalPicker.loading = false
      this.educationalPicker.columns = [res.data]
    })
    this.genderPicker.loading = true
    toolApi.getDicts('sys_user_sex').then(res => {
      this.genderPicker.loading = false
      this.genderPicker.columns = [res.data.filter(i => i.dictLabel !== '未知')]
    })
  },
  methods: {
    // 岗位类型选择器确认回调
    jobTypeConfirm({ value }) {
      this.form.jobType = value[0].dictValue
      this.form.jobTypeName = value[0].dictLabel
      this.jobTypePicker.show = false
    },
    // 学历选择器确认回调
    educationalConfirm({ value }) {
      this.form.educational = value[0].dictValue
      this.form.educationalName = value[0].dictLabel
      this.educationalPicker.show = false
    },
    // 性别选择器确认回调
    genderConfirm({ value }) {
      this.form.gender = value[0].dictValue
      this.form.genderName = value[0].dictLabel
      this.genderPicker.show = false
    },
    back() {
      uni.navigateBack()
    },
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      // 用于存储符合条件的图片
      let Images = [];
      // 遍历上传的每张图片
      for (let i = 0; i < lists.length; i++) {
        const item = lists[i];
        // 验证图片大小
        const maxSize = 20 * 1024 * 1024; // 2MB大小限制
        if (item.size > maxSize) {
          uni.showToast({
            title: '图片大小不能超过20MB',
            icon: 'none'
          });
          // 删除不符合条件的图片
          lists.splice(i, 1);
          // 跳过当前图片，进行下一张图片的验证
          continue;
        }
        Images.push(item)
      }
      let fileListLen = this[`fileList${event.name}`].length
      Images.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < Images.length; i++) {
        const result = await uni.$http.upload('/system/user/profile/upload', Images[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: result.status == 'failed' ? '上传失败' : '',
          url: config.baseUrl + result.imgUrl
        }))
        fileListLen++
      }
    },
    back() {
      uni.navigateBack()
    },
    async submit() {
      if (!this.fileList1.length) return uni.$showMsg('请先上传公司图片')
      await this.$refs.uForm.validate()
      const params = {
        ...this.form,
        images: this.fileList1.map(item => item.url.replace(config.baseUrl, '')).join(','),
        userId: this.user.userId,
        type: 4,
      }
      uni.showLoading({
        title: '加载中',
        mask: true,
      });
      try {
        await communityApi.addCommunity(params)
      } catch (error) {
        return
      } finally {
        uni.hideLoading()
      }
      uni.$showMsg('发布成功')
      setTimeout(() => {
        this.back()
      }, 1000)
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  box-sizing: border-box;
  height: 100vh;
  background-color: #f8f9fa;
  padding-top: 30rpx;
}

.register-form {
  box-sizing: border-box;
  padding: 25rpx 50rpx 35rpx;
  background-color: #fff;
  box-sizing: border-box;
  height: calc(100% - 200rpx);
  overflow-y: auto;

  &::v-deep .u-radio__text {
    margin-right: 15rpx;
  }
}

.submit {
  background-color: #fff;
  height: 200rpx;
  padding: 25rpx 40rpx 0;
}

.content::v-deep .u-form-item__body__left__content__label {
  width: 200rpx;
  margin-bottom: 15rpx;
}
.right-icon {
  display: flex;
  color: #999;
}
</style>
